package com.cskaoyan.controller;

import com.cskaoyan.anno.MyLog;
import com.cskaoyan.bean.system.Storage;
import com.cskaoyan.bean.system.Temp;
import com.cskaoyan.bo.system.*;
import com.cskaoyan.service.system.AdminService;
import com.cskaoyan.service.system.LogService;
import com.cskaoyan.service.system.RoleService;
import com.cskaoyan.service.system.StorageService;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.system.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@RestController
public class SystemController {

    @Autowired
    AdminService adminService;

    @Autowired
    LogService logService;

    @Autowired
    RoleService roleService;

    @Autowired
    StorageService storageService;


    @Value("${pic.storage-location}")
    private String picStorePath;

    @Value("${pic.fetch-url}")
    private String picStoreUrl;

    // ?page=1&limit=20&sort=add_time&order=desc
    // ?page=1&limit=20&username=ww&sort=add_time&order=desc 【搜索时】

    // @RequiresPermissions(value = {"admin:admin:list"}, logical = Logical.OR)
    @RequestMapping("admin/admin/list")
    @RequiresPermissions("admin:admin:list")
    public BaseRespVo adminList(AdminListBo adminListBo) {
        AdminListVo adminList = adminService.adminList(adminListBo);
        return BaseRespVo.ok(adminList);
    }

    // 使用hibernate validate时，注意不要忘了加@Valid！！！
    @MyLog
    @RequestMapping("admin/admin/create")
    @RequiresPermissions("admin:admin:create")
    public BaseRespVo adminCreate(@RequestBody @Valid AdminCreateBo adminCreateBo, BindingResult bindingResult) {

        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();

            // 获取出错的参数
            String field = fieldError.getField();

            if ("username".equals(field))
                return BaseRespVo.error(601, fieldError.getDefaultMessage());
            if ("password".equals(field))
                return BaseRespVo.error(602, fieldError.getDefaultMessage());
        }

        AdminCreateVo adminCreateVo = adminService.adminCreate(adminCreateBo);
        return BaseRespVo.ok(adminCreateVo);
    }

    @MyLog
    @RequestMapping("admin/admin/update")
    @RequiresPermissions("admin:admin:update")
    public BaseRespVo adminUpdate(@RequestBody AdminCreateBo adminCreateBo) {
        AdminCreateVo updateVo = adminService.adminUpdate(adminCreateBo);
        return BaseRespVo.ok(updateVo);
    }

    @MyLog
    @RequestMapping("admin/admin/delete")
    @RequiresPermissions("admin:admin:delete")
    public BaseRespVo adminDelete(@RequestBody AdminCreateBo adminCreateBo) {
        int code = adminService.delete(adminCreateBo);
        return BaseRespVo.ok();
    }

    // TODO：日志
    // TODO: 使用aspectj
    // ?page=1&limit=20&sort=add_time&order=desc
    // ?page=1&limit=20&name=admin12&sort=add_time&order=desc 【搜索时】
    @RequestMapping("admin/log/list")
    @RequiresPermissions("admin:log:list")
    public BaseRespVo logList(ListWithNameBo listWithNameBo) {
        LogListVo logListVo = logService.listLogs(listWithNameBo);
        return BaseRespVo.ok(logListVo);
    }


    // TODO：角色管理
    // ?page=1&limit=20&sort=add_time&order=desc
    // ?page=1&limit=20&name=2&sort=add_time&order=desc【查询时】

    // 工具：临时生成perm_all  表
    @RequestMapping("admin/permission/insert")
    public void permissionInsert(@RequestBody Temp temp) {
        roleService.permissionInsert(temp.getSystemPermissions());
    }

    @RequestMapping("admin/role/list")
    @RequiresPermissions("admin:role:list")
    public BaseRespVo roleList(ListWithNameBo listWithNameBo) {
        RoleListVo roleListVo = roleService.listRoles(listWithNameBo);
        return BaseRespVo.ok(roleListVo);
    }

    @RequestMapping("admin/role/create")
    @RequiresPermissions("admin:role:create")
    public BaseRespVo roleCreate(@RequestBody RoleCreateBo roleCreateBo) {
        RoleCreateVo roleCreateVo = roleService.createRole(roleCreateBo);
        return BaseRespVo.ok(roleCreateVo);
    }

    @GetMapping("admin/role/permissions")
    @RequiresPermissions("admin:role:permission:get")
    public BaseRespVo rolePermissions(Integer roleId) {
        PermissionsVo permissionsVo = roleService.rolePermissions(roleId);
        return BaseRespVo.ok(permissionsVo);
    }

    @PostMapping("admin/role/permissions")
    @RequiresPermissions("admin:role:permission:update")
    public BaseRespVo rolePermsUpdate(@RequestBody PermsUpdateBo permsUpdateBo) {
        roleService.updatePerms(permsUpdateBo);
        return BaseRespVo.ok();
    }

    @RequestMapping("admin/role/update")
    @RequiresPermissions("admin:role:update")
    public BaseRespVo roleUpdate(@RequestBody RoleCreateVo roleUpdateBo) {
        roleService.updateRole(roleUpdateBo);
        return BaseRespVo.ok();
    }

    @RequestMapping("admin/role/delete")
    @RequiresPermissions("admin:role:delete")
    public BaseRespVo roleDelete(@RequestBody RoleCreateVo roleDeleteBo) {
        roleService.deleteRole(roleDeleteBo.getId());
        return BaseRespVo.ok();
    }

    @RequestMapping("admin/role/options")
    // @RequiresPermissions("admin:role:options")
    public BaseRespVo roleOptions() {
        ArrayList<RoleOptionsVo> roleOptionsVos = roleService.roleOptions();
        return BaseRespVo.ok(roleOptionsVos);
    }

    // TODO：对象存储
    // ?page=1&limit=20&sort=add_time&order=desc
    // ?page=1&limit=20&key=w&name=2&sort=add_time&order=desc【查询时】
    @RequestMapping("admin/storage/list")
    @RequiresPermissions(value = "admin:storage:list")
    public BaseRespVo storageList(ListWithNameAndKeyBo listWithNameAndKeyBo) {
        StorageListVo storageListVo = storageService.listStorage(listWithNameAndKeyBo);
        return BaseRespVo.ok(storageListVo);
    }

    // TODO：索引key如何设置
    // 文件上传
    @RequestMapping(value = {"admin/storage/create", "wx/storage/upload"})
    public BaseRespVo storageCreate(MultipartFile file) {
        StorageCreateVo storageCreateBo = new StorageCreateVo();

        // 文件名称
        String originalFilename = file.getOriginalFilename();
        storageCreateBo.setName(originalFilename);

        // TODO:key和name的关系
        storageCreateBo.setKey(originalFilename);

        // 获取文件类型
        storageCreateBo.setType(file.getContentType());

        // 获取文件大小
        storageCreateBo.setSize(file.getSize());

        // http://localhost:8083/storage/fetch/+文件名当 作路径存入到数据库
        storageCreateBo.setUrl(picStoreUrl + originalFilename);

        // URL url = null;
        try {
            File storePath = new File(picStorePath);
            File targetFile = new File(storePath, originalFilename);
            file.transferTo(targetFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        StorageCreateVo storageCreateVo = storageService.storageCreate(storageCreateBo);
        return BaseRespVo.ok(storageCreateVo);
    }

    @RequestMapping("admin/storage/update")
    @RequiresPermissions("admin:storage:update")
    public BaseRespVo storageUpdate(@RequestBody Storage storage) {
        Storage storageVo = storageService.updateStorage(storage);
        return BaseRespVo.ok(storageVo);
    }

    @RequestMapping("admin/storage/delete")
    @RequiresPermissions("admin:storage:delete")
    public BaseRespVo storageDelete(@RequestBody Storage storage) {
        storageService.deleteStorageLogically(storage.getId());
        return BaseRespVo.ok();
    }

    // TODO：admin:storage:read

}
